package com.zhugang.week13.hash;

import java.util.HashMap;
import java.util.Map;

/**
 * @program algorithms
 * @description: singleNumber
 * @author: chanzhugang
 * @create: 2022/12/08 20:18
 */
public class SingleNumber {

    /**
     * 136、只出现一次的数字
     * https://leetcode.cn/problems/single-number/
     *
     * @param nums
     * @return
     */
    public int singleNumber(int[] nums) {
        /**
         * 哈希表统计频次
         */
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            int count = 1;
            if (map.containsKey(num)) {
                count += map.get(num);
            }
            map.put(num, count);
        }

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() == 1) {
                return entry.getKey();
            }
        }
        return -1;
    }

    public int singleNumber2(int[] nums) {
        int singleNum = 0;
        for (int num : nums) {
            // a⊕0=a
            // a⊕a=0
            // a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b
            // 异或运算，全部元素异或结果是只出现一次的数
            singleNum ^= num;
        }
        return singleNum;
    }


}